package br.com.californiahotel.server.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import br.com.californiahotel.client.service.ReservaService;
import br.com.californiahotel.server.hibernate.DatabaseUtils;
import br.com.californiahotel.server.hibernate.models.Apartamento;
import br.com.californiahotel.server.hibernate.models.Reserva;
import br.com.californiahotel.server.utils.Conversor;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class ReservaServiceImpl extends RemoteServiceServlet implements ReservaService {

	private static final DatabaseUtils<Apartamento> APTO_DATABASE = new DatabaseUtils<Apartamento>();
	private static final Class<Reserva> RESERVA_CLASS = br.com.californiahotel.server.hibernate.models.Reserva.class;
	private static final DatabaseUtils<Reserva> DATABASE = new DatabaseUtils<Reserva>();
	private static final Conversor CONVERSOR = new Conversor();

	@Override
	public boolean save(br.com.californiahotel.shared.models.Reserva model) {
		try {
			Reserva reserva =  CONVERSOR.convertReservaModelToReservaHibernate(model);
			reserva.setApartamento(APTO_DATABASE.find(Apartamento.class, Integer.parseInt(model.getApartamento())));
			DATABASE.save(reserva);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean edit(br.com.californiahotel.shared.models.Reserva model, String id) {
		try {
			DATABASE.removeById(RESERVA_CLASS, id);
			DATABASE.save((Reserva)CONVERSOR.convertModelToHibernate( model, RESERVA_CLASS));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public List<br.com.californiahotel.shared.models.Reserva> findAll() {
		ArrayList<br.com.californiahotel.shared.models.Reserva> ReservaList = new ArrayList<br.com.californiahotel.shared.models.Reserva>();
		List<Reserva> findAll = DATABASE.findAll(RESERVA_CLASS);
		for (Reserva Reserva : findAll) {
			ReservaList.add(CONVERSOR.convertReservaHibernateToReservaModel(Reserva));
		}
		return ReservaList;
	}

	@Override
	public boolean delete(String key) {
		try {
			DATABASE.removeById(RESERVA_CLASS, Long.parseLong(key));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
